package com.sky.utils;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.sky.result.Result;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.UUID;

@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {

    private String endpoint;
    private String bucketName;
    private String region;

    //获取环境变量,以便从环境变量中获取访问凭证
    final static private EnvironmentVariableCredentialsProvider credentialsProvider = new EnvironmentVariableCredentialsProvider();

    /** 生成唯一的一个文件名 */
    public static String generateUniqueBucketName(String fileName)
    {
        String uuidFileName = UUID.randomUUID().toString().replace("-", "") +
                fileName.substring(fileName.lastIndexOf("."));
        return uuidFileName;
    }


    /**
     * 文件上传
     *
     * @param multipartFile 上传文件
     * @return
     */
    public Result upload(MultipartFile multipartFile) throws IOException {
        log.info("{}",multipartFile.getName());
        //创建 OSSClient 实例
        ClientBuilderConfiguration clientBuilerConfiguration = new ClientBuilderConfiguration();
        //使用V4签名算法对 AccessKey 加密
        clientBuilerConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .clientConfiguration(clientBuilerConfiguration)
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .region(region)
                .build();
        //随机文件名字
        String fileName = generateUniqueBucketName(multipartFile.getOriginalFilename());
        //获取 oss 输出流
        try
        {

            //创建PutobjectRequest实例
                    PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, new ByteArrayInputStream(multipartFile.getBytes()));
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            //上传文件
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        }finally
        {
            log.info("关闭oss资源");
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        //获取文件路径
        StringBuilder stringBuilder = new StringBuilder("https://");
		//文件访问路径规则 https://yuxi-oss.oss-cn-fuzhou.aliyuncs.com/fileName
        stringBuilder.append(bucketName);
        stringBuilder.append(".");
        stringBuilder.append(endpoint);
        stringBuilder.append("/");
        stringBuilder.append(fileName);
        String fileUrl = stringBuilder.toString();
        log.info("文件上传到:{}", fileUrl);
        return Result.success(fileUrl);
    }

    public void delete(String fileName){
        log.info("删除文件:{}",fileName);
        //创建 OSSClient 实例
        ClientBuilderConfiguration clientBuilerConfiguration = new ClientBuilderConfiguration();
        //使用V4签名算法对 AccessKey 加密
        clientBuilerConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .clientConfiguration(clientBuilerConfiguration)
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .region(region)
                .build();
        try{
            ossClient.deleteObject(bucketName, fileName);
        }finally
        {
            log.info("关闭oss资源");
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
